package com.csun.cmny.provider.controller;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.dao.OldmanItemMapper;
import com.csun.cmny.provider.dto.ExpenseCtrItemQueryDto;
import com.csun.cmny.provider.dto.ShowAllItemDto;
import com.csun.cmny.provider.entity.JsonResult;
import com.csun.cmny.provider.pojo.*;
import com.csun.cmny.provider.service.ExpCtrItemService;
import com.csun.cmny.provider.service.ExpenseCtrService;
import com.csun.cmny.provider.service.SetMealService;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/*
 * 类别下的项目管理
 * */
@Slf4j
@RestController
@RequestMapping("/ExpCtrItem")
public class ExpCtrItemController extends BaseController {
    @Autowired
    private ExpCtrItemService expCtrItemService;
    @Autowired
    private ExpenseCtrService expenseCtrService;
    @Autowired
    private SetMealService setMealService;


    /*
     * 这里的认证和当前登录的用户注解先预留，等完善了再进行修改
     * 1.判断该用户是否属于该机构人员
     * */
    //添加项目
    @RequestMapping(value = "/addExpCtrItem", method = RequestMethod.POST)
    public Wrapper addExpCtrItem(ExpCtrItem expCtrItem) {
        //校验
        if (org.apache.commons.lang.StringUtils.isBlank(expCtrItem.getItemName())) {
            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"项目名称不能为空",null);
        }
        if (org.apache.commons.lang.StringUtils.isBlank(expCtrItem.getContent())) {
            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"项目内容不能为空",null);
        }
        if (expCtrItem.getExpensectrId() == null) {
            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"类别id不能为空",null);
        }
        if (expCtrItem.getCostType() == null) {
            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"项目服务频次不能为空",null);
        }
        if (expCtrItem.getChargeStandard() == null) {
            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"项目收费标准不能为空",null);
        }
        //获取机构id
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        Integer homeId = loginAuthDto.getGroupId().intValue();
        ExpenseCtr expenseCtr = new ExpenseCtr();
        expenseCtr.setExpensectrId(expCtrItem.getExpensectrId());
        expenseCtr.setHomeId(homeId);
        //判断该社区是否有该类别
        ExpenseCtr expenseCtr1 = expenseCtrService.selectByExpCtr(expenseCtr);
        if (expenseCtr1 == null) {
            return  WrapMapper.wrap(Wrapper.ERROR_CODE,"该社区没有该类别",null);
        }
        //如果该项目是额外添加的类别下的，则修改该类别的isDelete值自动加一
        if (expenseCtr1.getHomeId() != null) {
            expenseCtr1.setIsDelete(expenseCtr1.getIsDelete() + 1);
            int n = expenseCtrService.updateExpCtrById(expenseCtr1);
        }

        //判重——判断该项目是否在该类别中已经存在
        ExpenseCtr expenseCtr2 = new ExpenseCtr();
        expenseCtr2.setExpensectrId(expenseCtr1.getExpensectrId());
        //根据类别id查询类别及类别下的所有项目
       List<ExpenseCtr> expenseCtrList = expenseCtrService.selectOne(expenseCtr);
        if (!CollectionUtils.isEmpty(expenseCtrList) && expenseCtrList.size() == 1) {
            List<ExpCtrItem> expCtrItemList = expenseCtrList.get(0).getExpCtrItemList();
            if (!CollectionUtils.isEmpty(expCtrItemList)) {
                for (int i = 0; i <expCtrItemList.size() ; i++) {
                    if (expCtrItemList.get(i).getItemName().equals(expCtrItem.getItemName())) {
                        return  WrapMapper.wrap(Wrapper.ERROR_CODE,"该项目已经存在该类别中",null);
                    }
                }
            }
        }else {
            return  WrapMapper.wrap(Wrapper.ERROR_CODE,"根据类别id查询出了多个类别",null);
        }
        expCtrItem.setType(0);
        expCtrItem.setIsDelete(0);
        expCtrItem.setHomeId(homeId);
        int n = expCtrItemService.insert(expCtrItem);
        if (n <= 0) {
            return  WrapMapper.wrap(Wrapper.ERROR_CODE,"添加失败",0);
        }
        return  WrapMapper.wrap(Wrapper.SUCCESS_CODE,"添加成功", expCtrItem.getExpensectrId());
    }

    //根据id删除项目
    @RequestMapping(value = "/delExpCtrItemById", method = RequestMethod.POST)
    public Wrapper delExpCtrItemById(Integer itemId) {
        if (itemId == null) {
            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"项目id不能为空",null);
        }
        /*
        *删除前判断该类别下是否有项目在套餐被使用，如果被使用则不能删除
        */
        ExpCtrItem expCtrItem = expCtrItemService.selectById(itemId);
        if (expCtrItem == null) {
            return  WrapMapper.wrap(Wrapper.ERROR_CODE,"没有此id",itemId);
        }
        //判断能否删除
        Integer isDelete = expCtrItemService.newIsItemBeUsed(itemId);
        if (isDelete!=0){
            return  WrapMapper.wrap(Wrapper.ERROR_CODE,"该服务项目被使用中,无法删除或修改",itemId);
        }

        /**
         * @date    2019-05-07
         * @author  chisj
         * @desc    修复已经在使用的服务项目不能修改bug #1840
         */
        // 判断是否在套餐里面
        List<Map<String,Object>> tmpList = setMealService.selectByItemId(expCtrItem.getItemId());
        if (PublicUtil.isNotEmpty(tmpList)) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"该服务项目被使用中,无法删除或修改",expCtrItem.getItemId());
        }

        ExpenseCtr expenseCtr = expenseCtrService.selectById(expCtrItem.getExpensectrId());
        ExpenseCtr newExpCtrItem = new ExpenseCtr();
        newExpCtrItem.setExpensectrId(expenseCtr.getExpensectrId());
        newExpCtrItem.setIsDelete(expenseCtr.getIsDelete()-1);
        expenseCtrService.updateExpCtrById(newExpCtrItem);
        int n = expCtrItemService.delExpCtrItemById(itemId);
        if (n <= 0) {
            return  WrapMapper.wrap(Wrapper.ERROR_CODE,"没有此id",itemId);
        }
        return  WrapMapper.wrap(Wrapper.SUCCESS_CODE,"删除成功",n);
    }

    //修改项目
    /*
    * 一旦将项目的收费标准进行了修改，1.对应的套餐也要对项目折后价进行修改 2.对应的套餐总价也要修改
    * */
    @RequestMapping(value = "/updateExpCtrItem", method = RequestMethod.POST)
    public Wrapper updateExpCtrItem(ExpCtrItem expCtrItem){
        //校验
        if (expCtrItem.getItemId() == null) {
            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"项目id不能为空",null);
        }
        //判断能否删除
        Integer isDelete = expCtrItemService.newIsItemBeUsed(expCtrItem.getItemId());
        if (isDelete > 0){
            return  WrapMapper.wrap(Wrapper.ERROR_CODE,"该服务项目被使用中,无法删除或修改",expCtrItem.getItemId());
        }

        /**
         * @date    2019-05-07
         * @author  chisj
         * @desc    修复已经在使用的服务项目不能修改bug #1840
         */
        // 判断是否在套餐里面
        List<Map<String,Object>> tmpList = setMealService.selectByItemId(expCtrItem.getItemId());
        if (PublicUtil.isNotEmpty(tmpList)) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE,"该服务项目被使用中,无法删除或修改",expCtrItem.getItemId());
        }

        //获取机构id
        LoginAuthDto loginAuthDto = getLoginAuthDto();
        Integer homeId = loginAuthDto.getGroupId().intValue();
        //根据id查询该项目信息
        ExpCtrItem expCtrItem1 = expCtrItemService.selectById(expCtrItem.getItemId());
        if (org.apache.commons.lang.StringUtils.isNotBlank(expCtrItem.getItemName())) {
            ExpenseCtr expenseCtr = new ExpenseCtr();
            expenseCtr.setExpensectrId(expCtrItem1.getExpensectrId());
            //判重——判断该项目是否在该类别中已经存在
            //根据类别id查询类别及类别下的所有项目
            List<ExpenseCtr> expenseCtrList = expenseCtrService.selectOne(expenseCtr);
            if (!CollectionUtils.isEmpty(expenseCtrList) && expenseCtrList.size() == 1) {
                List<ExpCtrItem> expCtrItemList = expenseCtrList.get(0).getExpCtrItemList();
                if (!CollectionUtils.isEmpty(expCtrItemList)) {
                    for (int i = 0; i <expCtrItemList.size() ; i++) {
                        if (expCtrItemList.get(i).getItemName().equals(expCtrItem.getItemName()) && expCtrItemList.get(i).getItemId().intValue() != expCtrItem.getItemId().intValue()) {
                            return  WrapMapper.wrap(Wrapper.ERROR_CODE,"该项目已经存在该类别中",null);
                        }
                    }
                }
            }else if (expenseCtrList.size() > 1) {
                return  WrapMapper.wrap(Wrapper.ERROR_CODE,"根据类别id查询出了多个类别",null);
            }
        }

        //修改
        int a = expCtrItemService.updateExpCtrById(expCtrItem);

        if (expCtrItem.getChargeStandard() != null && expCtrItem1.getChargeStandard().intValue() != expCtrItem.getChargeStandard().intValue()) {
            //修改套餐总价
            //查询使用了该项目的套餐集合
            List<Map<String,Object>> mapList = setMealService.selectByItemId(expCtrItem.getItemId());
            if (!CollectionUtils.isEmpty(mapList)) {
                List<Integer> integerList = new ArrayList<>();//套餐id集合
                for (int i = 0; i <mapList.size() ; i++) {
                    //获取id
                    integerList.add((Integer) mapList.get(i).get("setMealId"));
                    //如果收费标准进行了修改，那么修改套餐-项目关系表中的项目折后价
                    //根据项目id从套餐-项目关系表中查询包含该项目的数据
                    String discount = (String) mapList.get(i).get("discount");
                    if (PublicUtil.isNotEmpty(discount)) {
                        //获取现收费标准折后的价格
                        BigDecimal afterDis = expCtrItem.getChargeStandard().multiply(new BigDecimal(discount)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        //覆盖原集合中的折后价格
                        mapList.get(i).put("afterDis", afterDis);
                    }
                }
                //修改套餐-项目关系表中项目的折后价格
                int n = setMealService.updateBatch(mapList);
                if (n <= 0) {
                    System.out.println("********************修改项目收费标准时,修改套餐-项目关系表中项目的折后价格失败********************");
                }
                //查询使用了该项目的套餐及项目详细信息集合
                List<SetMeal> setMealList = setMealService.selectByList(integerList);
                if (!CollectionUtils.isEmpty(setMealList)) {
                    for (int i = 0; i <setMealList.size() ; i++) {
                        List<SetMealExpItem> setMealExpItemList = setMealList.get(i).getSetMealExpItemList();
                        if (!CollectionUtils.isEmpty(setMealExpItemList)) {
                            BigDecimal beforeDis = new BigDecimal(0.00);
                            BigDecimal afterDis = new BigDecimal(0.00);
                            for (int j = 0; j <setMealExpItemList.size() ; j++) {
                                /**
                                 * @date    2019-05-06
                                 * @author  chisj
                                 * @desc    修复bug #1833
                                 */
                                if (PublicUtil.isEmpty(setMealExpItemList.get(j).getExpCtrItem())) {
                                    continue;
                                }
                                //求套餐折前总价
                                beforeDis = beforeDis.add(setMealExpItemList.get(j).getExpCtrItem().getChargeStandard().multiply(new BigDecimal(setMealExpItemList.get(j).getDays())).setScale(2, BigDecimal.ROUND_HALF_UP));
                                //求套餐折后总价
                                int days = setMealExpItemList.get(j).getDays();
                                BigDecimal tmp = setMealExpItemList.get(j).getAfterDis();
                                if (PublicUtil.isNotEmpty(tmp)) {
                                    afterDis = afterDis.add(tmp.multiply(new BigDecimal(days)).setScale(2, BigDecimal.ROUND_HALF_UP));
                                }
                            }
                            setMealList.get(i).setBeforeDis(beforeDis);
                            setMealList.get(i).setAfterDis(afterDis);
                        }
                    }
                    //批量修改套餐
                    int m = setMealService.updateSMBatch(setMealList);
                    if (m <= 0) {
                        System.out.println("********************修改项目收费标准时,批量修改套餐失败********************");
                    }
                }
            }
        }

        if (a <= 0) {
            return  WrapMapper.wrap(Wrapper.ERROR_CODE,"修改失败",0);
        }
        return  WrapMapper.wrap(Wrapper.SUCCESS_CODE,"修改成功",a);
    }

    //根据项目id查询项目
    @RequestMapping(value = "/selectById", method = RequestMethod.POST)
    public Wrapper selectById(Integer itemId) {
        //校验
        if (itemId == null) {
            return  WrapMapper.wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_,"项目id不能为空",itemId);
        }
        ExpCtrItem expCtrItem = expCtrItemService.selectById(itemId);
        if (expCtrItem == null) {
            return  WrapMapper.wrap(Wrapper.ERROR_CODE,"没有此id",itemId);
        }
        return  WrapMapper.wrap(Wrapper.SUCCESS_CODE,"查询成功",expCtrItem);
    }

    /**
     * 根据条件查询社区所有收费项目
     * @param
     * @return
     */
    @RequestMapping(value = "/showAll", method = RequestMethod.POST)
    public Wrapper showAll( @RequestBody ShowAllItemDto showAllItemDto) {
        String pageNo = showAllItemDto.getPageNo();
        String pageSize = showAllItemDto.getPageSize();

        if (StringUtils.isEmpty(pageNo)) {
            pageNo = "1";
        }
        if (StringUtils.isEmpty(pageSize)) {
            pageSize = "10";
        }
        //当前登录用户获取机构id
       /* LoginAuthDto loginAuthDto = getLoginAuthDto();
        Integer homeId = loginAuthDto.getGroupId().intValue();
        showAllItemDto.setHomeId(homeId);*/
        PageHelper.startPage(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
        List<Map<String,Object>> mapList = expCtrItemService.showAll(showAllItemDto);
        PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(mapList);
        if (CollectionUtils.isEmpty(mapList)) {
            return  WrapMapper.wrap(Wrapper.ERROR_CODE,"没有查询到结果", new ArrayList<>());
        }
        return  WrapMapper.wrap(Wrapper.SUCCESS_CODE,"查询成功",pageInfo);
    }

    @RequestMapping(value = "/queryItemListWithPage", method = RequestMethod.POST)
    public Wrapper queryItemListWithPage(@RequestBody ExpenseCtrItemQueryDto expenseCtrItemQueryDto) {

        expenseCtrItemQueryDto.setHomeId(getLoginAuthDto().getGroupId().intValue());
        PageInfo pageInfo = expCtrItemService.queryItemListWithPage(expenseCtrItemQueryDto);

        return WrapMapper.ok(pageInfo);
    }
}
